<template>
	<view class="content" v-if="isShow" @click.stop="isShow=false">
		<canvas @click.stop="" :style="{ width: canvasW + 'px', height: canvasH + 'px' }" canvas-id="my-canvas"></canvas>
		<!-- <view class="save-btn" @click.stop="saveImage">保存图片</view> -->
		 
			<u-row style="width: 750rpx;margin-top: 16rpx;" justify='space-around'>
				<u-col span='6'  justify='center' @click="shareBywx">
					<u-row justify='center'>
						<u--image :showLoading="true"
						src="/static/icon/weixin.png" width="80px" height="80px" @click="click"></u--image>
						
					</u-row>
					<u--text  text='分享到微信' align='center'></u--text> 
				</u-col>
				 
				<u-col  span='6' @click="shareBywxpyq"  justify='center'>
					<u-row justify='center'>
						<u--image :showLoading="true"  src="/static/icon/wxpyq.png" width="80px" height="80px" @click="click"></u--image>
					</u-row>
					<u--text text='分享到朋友圈' align='center'></u--text>
				</u-col>
			</u-row>
		 
	</view>
</template>

<script>
	import QRCodeAlg from './QRCodeAlg.js';
	export default{
		props:{
			qrCode:{
				type: String,
				default: '有方练车'
			},
			headerImg:{
				type: String,
				default: 'https://servicetall.oss-cn-beijing.aliyuncs.com/saas/common/337de06b759e04cbdfc07f56d865ce2f33fa2de3.jpg'
			},
			title:{
				type: String,
				default: '草莓千层蛋糕'
			},
			subTitle:{
				type: String,
				default: '鲜嫩多汁的草莓融合香甜奶油'
			},
			price:{
				type: Number,
				default: 36.89
			},
			abImg:{
				type: String,
				default: 'https://servicetall.oss-cn-beijing.aliyuncs.com/saas/common/337de06b759e04cbdfc07f56d865ce2f33fa2de3.jpg'
			}
		},
		data(){
			return {
				canvasW: 0,
				canvasH: 0,
				ctx: null,
				isShow: false,
				qrcode: '../../../static/logo.png'
			}
		},
		methods:{
			//显示
			showCanvas(){
				this.isShow = true
				this.__init()
			},
			//初始化画布
			async __init(){
				uni.showLoading({
				    title: '加载中...',
					mask: true
				})
				this.ctx = uni.createCanvasContext('my-canvas',this)
				this.canvasW = uni.upx2px(570);
				this.canvasH = uni.upx2px(900);
				//设置画布背景透明
				this.ctx.setFillStyle('rgba(255, 255, 255, 0)')
				//设置画布大小
				this.ctx.fillRect(0,0,this.canvasW,this.canvasH)
				//绘制圆角背景
				this.drawRoundRect(this.ctx, 0, 0, this.canvasW, this.canvasH,uni.upx2px(18),'#FFFFFF')
				//获取标题图片 
				let headerImg = await this.getImageInfo(this.headerImg)
				console.log('获取标题图片',headerImg)
				let hW = uni.upx2px(500);
				let hH = uni.upx2px(450);
				//绘制标题图
				this.drawRoundImg(this.ctx,headerImg.path,((this.canvasW-hW) / 2),((this.canvasW-hW) / 2),hW,hH,8)
				//绘制标题
				this.ctx.setFontSize(18); //设置标题字体大小
				this.ctx.setFillStyle('#333'); //设置标题文本颜色
				this.ctx.fillText(this.title,((this.canvasW-hW) / 2),(((this.canvasW-hW) / 2) + hH +30 ))
				//绘制副标题
				this.ctx.setFontSize(14);
				this.ctx.setFillStyle('#858585');
				let sWidth = this.ctx.measureText(this.subTitle).width
				if(sWidth > hW){
					this.ctx.fillText(this.subTitle.slice(0,19) + '...',((this.canvasW-hW) / 2),(
					((this.canvasW-hW) / 2) + hH + 45))
				}else{
					this.ctx.fillText(this.subTitle,((this.canvasW-hW) / 2),(
					((this.canvasW-hW) / 2) + hH + 45))
				}
				//绘制价格
				// this.ctx.setFontSize(14);
				// this.ctx.setFillStyle('#f54545');
				// this.ctx.fillText('￥',((this.canvasW-hW) / 2),(
				// ((this.canvasW-hW) / 2) + hH + 90))
				// this.ctx.setFontSize(18);
				// this.ctx.fillText(this.price,(((this.canvasW-hW) / 2) + 18),(
				// ((this.canvasW-hW) / 2) + hH + 90))
				//绘制虚线
				this.drawDashLine(this.ctx,10,(((this.canvasW-hW) / 2) + hH + 70),(this.canvasW-10),(((this.canvasW-hW) / 2) + hH + 70),5)
				//左边实心圆
				this.drawEmptyRound(this.ctx,0,(((this.canvasW-hW) / 2) + hH + 70),10)
				//右边实心圆
				this.drawEmptyRound(this.ctx,this.canvasW,(((this.canvasW-hW) / 2) + hH + 70),10)
				//提示文案
				this.ctx.setFontSize(12);
				this.ctx.setFillStyle('#858585');
				this.ctx.fillText('长按识别图中“二维码”下载',20,(((this.canvasW-hW) / 2) + hH + 60))
				//底部广告
				let BottomAdImg = await this.getImageInfo(this.abImg)
				console.log('底部广告',BottomAdImg)
				// this.ctx.drawImage(BottomAdImg.path,30,(((this.canvasW-hW) / 2) + hH + 100),135,80)
				//小程序码
				let qrcodeImg = await this.getImageInfo(this.qrcode) 
				this.drawQrCode(this.ctx,{
					// image:this.qrcode,
					// imageSize:25,
					text: this.qrCode, 
					size: 100,
					dx: ( this.canvasW /2 - 50 ) ,
					dy: (((this.canvasW-hW) / 2) + hH + 80)
				})
				// this.ctx.drawImage(qrcodeImg.path,228,(((this.canvasW-hW) / 2) + hH + 100), 95, 95)
				//延迟渲染
				setTimeout(()=>{
					this.ctx.draw(true,()=>{
						uni.hideLoading()
					})
				},500)
			},
			//绘制实心圆
			drawEmptyRound(ctx,x,y,radius){
				ctx.save()
				ctx.beginPath();
				ctx.arc(x, y, radius, 0, 2 * Math.PI,true);
				ctx.setFillStyle('rgba(0, 0, 0, .4)')
				ctx.fill();
				ctx.restore()
				ctx.closePath()
			},
			//绘制虚线
			drawDashLine(ctx,x1,y1,x2,y2,dashLength){
				ctx.setStrokeStyle("#cccccc")//设置线条的颜色
				ctx.setLineWidth(1)//设置线条宽度
				var dashLen = dashLength,
				xpos = x2 - x1, //得到横向的宽度;
				ypos = y2 - y1, //得到纵向的高度;
				numDashes = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen); 
				//利用正切获取斜边的长度除以虚线长度，得到要分为多少段;
				for(var i=0; i<numDashes; i++){
				 if(i % 2 === 0){
					 ctx.moveTo(x1 + (xpos/numDashes) * i, y1 + (ypos/numDashes) * i); 
					 //有了横向宽度和多少段，得出每一段是多长，起点 + 每段长度 * i = 要绘制的起点；
				  }else{
					  ctx.lineTo(x1 + (xpos/numDashes) * i, y1 + (ypos/numDashes) * i);
				  }
				}
				ctx.stroke();
			},
			//带圆角图片
			drawRoundImg(ctx, img, x, y, width, height, radius){
				ctx.beginPath()
				ctx.save()
				// 左上角
				ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5)
				// 右上角
				ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2)
				// 右下角
				ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5)
				// 左下角
				ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI)
				ctx.stroke()
				ctx.clip()
				ctx.drawImage(img, x, y, width, height);
				ctx.restore()
				ctx.closePath()
			},
			//圆角矩形
			drawRoundRect(ctx, x, y, width, height, radius, color){
				ctx.save();
				ctx.beginPath();
				ctx.setFillStyle(color); 
				ctx.setStrokeStyle(color)
				ctx.setLineJoin('round');  //交点设置成圆角
				ctx.setLineWidth(radius);
				ctx.strokeRect(x + radius/2, y + radius/2, width - radius , height - radius );
				ctx.fillRect(x + radius, y + radius, width - radius * 2, height - radius * 2);
				ctx.stroke();
				ctx.closePath();
			},
			//二维码
			drawQrCode(Context, qrCodeObj){
				let qrcodeAlgObjCache = [];
				let options = {
					text: String(qrCodeObj.text || '') || '', // 生成内容
					size: Number(qrCodeObj.size || 0) || 200, // 二维码大小
					background: String(qrCodeObj.background || '') || '#ffffff', // 背景色
					foreground: String(qrCodeObj.foreground || '') || '#000000', // 前景色
					pdground: String(qrCodeObj.pdground || '') || '#000000', // 定位角点颜色
					correctLevel: Number(qrCodeObj.correctLevel || 0) || 3, // 容错级别
					image: String(qrCodeObj.image || '') || '', // 二维码图标
					imageSize: Number(qrCodeObj.imageSize || 0) || 40, // 二维码图标大小
					dx: Number(qrCodeObj.dx || 0) || 0, // x轴距离
					dy: Number(qrCodeObj.dy || 0) || 0 // y轴距离
				}
				let qrCodeAlg = null;
				let d = 0;
				for (var i = 0, l = qrcodeAlgObjCache.length; i < l; i++) {
					d = i;
					if (qrcodeAlgObjCache[i].text == options.text && qrcodeAlgObjCache[i].text.correctLevel == options.correctLevel) {
						qrCodeAlg = qrcodeAlgObjCache[i].obj;
						break;
					}
				}
				if (d == l) {
					qrCodeAlg = new QRCodeAlg(options.text, options.correctLevel);
					qrcodeAlgObjCache.push({
						text: options.text,
						correctLevel: options.correctLevel,
						obj: qrCodeAlg
					});
				}
				let getForeGround = function(config) {
					let options = config.options;
					if (options.pdground && (
							(config.row > 1 && config.row < 5 && config.col > 1 && config.col < 5) ||
							(config.row > (config.count - 6) && config.row < (config.count - 2) && config.col > 1 && config.col < 5) ||
							(config.row > 1 && config.row < 5 && config.col > (config.count - 6) && config.col < (config.count - 2))
						)) {
						return options.pdground;
					}
					return options.foreground;
				}
				let count = qrCodeAlg.getModuleCount();
				let ratioSize = options.size;
				let ratioImgSize = options.imageSize;
				//计算每个点的长宽
				let tileW = (ratioSize / count).toPrecision(4);
				let tileH = (ratioSize / count).toPrecision(4);
				//绘制
				for (let row = 0; row < count; row++) {
					for (let col = 0; col < count; col++) {
						let w = (Math.ceil((col + 1) * tileW) - Math.floor(col * tileW));
						let h = (Math.ceil((row + 1) * tileW) - Math.floor(row * tileW));
						let foreground = getForeGround({
							row: row,
							col: col,
							count: count,
							options: options
						});
						Context.setFillStyle(qrCodeAlg.modules[row][col] ? foreground : options.background);
						Context.fillRect(options.dx + Math.round(col * tileW), options.dy + Math.round(row * tileH), w, h);
					}
				}
				if (options.image) {
					let x = options.dx + Number(((ratioSize - ratioImgSize) / 2).toFixed(2));
					let y = options.dy + Number(((ratioSize - ratioImgSize) / 2).toFixed(2));
					drawRoundedRect(Context, x, y, ratioImgSize, ratioImgSize, 2, 6, true, true)
					Context.drawImage(options.image, x, y, ratioImgSize, ratioImgSize);
					// 画圆角矩形
					function drawRoundedRect(ctxi, x, y, width, height, r, lineWidth, fill, stroke) {
						ctxi.setLineWidth(lineWidth);
						ctxi.setFillStyle(options.background);
						ctxi.setStrokeStyle(options.background);
						ctxi.beginPath(); // draw top and top right corner 
						ctxi.moveTo(x + r, y);
						ctxi.arcTo(x + width, y, x + width, y + r, r); // draw right side and bottom right corner 
						ctxi.arcTo(x + width, y + height, x + width - r, y + height, r); // draw bottom and bottom left corner 
						ctxi.arcTo(x, y + height, x, y + height - r, r); // draw left and top left corner 
						ctxi.arcTo(x, y, x + r, y, r);
						ctxi.closePath();
						if (fill) {
							ctxi.fill();
						}
						if (stroke) {
							ctxi.stroke();
						}
					}
				}
			},
			//获取图片
			getImageInfo(imgSrc){
				console.log('getImageInfo',imgSrc)
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: imgSrc,
						success: (image) => {
							resolve(image);
							console.log('获取图片成功',image)
						},
						fail: (err) => {
							reject(err);
							console.log('获取图片失败',err)
						}
					});
				});
			},
			//朋友圈
			shareBywxpyq(){
				var that = this
				uni.canvasToTempFilePath({
					canvasId: 'my-canvas',
					quality: 1,
					complete: (res) => {
					 uni.share({ 
					 	    // scene: "WXSceneTimeline",
					 	    // type: 0,
					 	    // href: "http://wpa.qq.com/msgrd?v=3&uin=184773349&site=qq&menu=yes",
					 	    // title: "帅人的分享，你不看看？",
					 	    // summary: "和我体验体验作为开发者的快乐呗",
					 	    // imageUrl: this.posterUrl,
					 		provider: "weixin",
					 		scene:'WXSceneTimeline',
					 		type: 2,
					 		imageUrl:res.tempFilePath,
					 		 
					 	success: function (res) {
					 		console.log("success:" + JSON.stringify(res));
					 		uni.showToast({
					 			title: '分享成功',
					 			icon:'success',
					 			duration:1000
					 		});
					 	},
					 	fail: function (err) {
					 		
					 		uni.showToast({
					 			title: '分享失败',
					 			icon:'error',
					 			duration:1000
					 		});
					 		console.log("fail:" + JSON.stringify(err));
					 	}
					 	
					 })
					}
				},this);
				
			},
			//分享到好友
			shareBywx(){
				var that = this
				uni.canvasToTempFilePath({
					canvasId: 'my-canvas',
					quality: 1,
					complete: (res) => {
					 uni.share({
					 	 provider: "weixin",
					 	    // scene: "WXSceneTimeline",
					 	    // type: 0,
					 	    // href: "http://wpa.qq.com/msgrd?v=3&uin=184773349&site=qq&menu=yes",
					 	    // title: "帅人的分享，你不看看？",
					 	    // summary: "和我体验体验作为开发者的快乐呗",
					 	    // imageUrl: this.posterUrl,
					 		provider: "weixin",
					 		scene:'WXSceneSession',
					 		type: 2,
					 		imageUrl:res.tempFilePath,
					 		 
					 	success: function (res) {
					 		console.log("success:" + JSON.stringify(res));
					 		uni.showToast({
					 			title: '分享成功',
					 			icon:'success',
					 			duration:1000
					 		});
					 	},
					 	fail: function (err) {
					 		
					 		uni.showToast({
					 			title: '分享失败',
					 			icon:'error',
					 			duration:1000
					 		});
					 		console.log("fail:" + JSON.stringify(err));
					 	}
					 	
					 })
					}
				},this);

			},
			//保存图片到相册
			saveImage(){
				console.log('保存')
				//判断用户授权
				uni.getSetting({
				   success(res) {
				      console.log('获取用户权限',res.authSetting)
					  if(Object.keys(res.authSetting).length>0){
						  //判断是否有相册权限
						  if(res.authSetting['scope.writePhotosAlbum']==undefined){
							  //打开设置权限
							  uni.openSetting({
							    success(res) {
							      console.log('设置权限',res.authSetting)
							    }
							  })
						  }else{
							  if(!res.authSetting['scope.writePhotosAlbum']){
								  //打开设置权限
								  uni.openSetting({
								    success(res) {
								      console.log('设置权限',res.authSetting)
								    }
								  })
							  }
						  }
					  }else{
						  return
					  }
				   }
				})
				var that = this
				uni.canvasToTempFilePath({
					canvasId: 'my-canvas',
					quality: 1,
					complete: (res) => {
						console.log('保存到相册',res);
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success(res) {
								uni.showToast({
									title: '已保存到相册',
									icon: 'success',
									duration: 2000
								})
								setTimeout(()=>{
									that.isShow = false
								},2000)
							}
						})
					}
				},this);
			}
		}
	}
</script>

<style scoped lang="scss">
.content{
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0,0,0,.4);
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	.save-btn{
		margin-top: 35rpx;
		color: #FFFFFF;
		background: linear-gradient(to right, #2aa9fe , #96b7fe);
		padding: 15rpx 40rpx;
		border-radius: 50rpx;
	}
}
</style>
